package com.games.ecoship.server;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.games.ecoship.EcoShipConstants;


public class EcoShipServer extends JFrame implements EcoShipConstants {

	private static final long serialVersionUID = 8190166401566892923L;
	
	private static final String TITLE_TEXT     = "Eco-Ship Server"; 
	private static final Point  DIMENSIONS     = new Point(600,200);
	
	private JTextArea           logText        = null;
	private int                 sessionNum     = 1;
	private Boolean             serverRunning  = true;
	
	public static void main(String[] args) {
		new EcoShipServer();
	}
	
	public EcoShipServer() {
		
		// Create panel to display server info
		initGUI();
		
		try {
			// Create Server Socket
			ServerSocket socket = new ServerSocket(PORT_NUM);
			
			// Ready to create a new session for every two players
			while (serverRunning) {
				
				// Date
				logText.append(new Date() + ": Waiting for players to join session " + '\n');
				
				// Connect to player 1
				Socket player1 = socket.accept();
				logText.append(new Date() + ": Player 1 joined session " + sessionNum + '\n');
				logText.append(new Date() + ": Player 1 IP Adress: " + player1.getInetAddress().getHostAddress() + '\n');
				new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1);
				
				// Connect to player 2
				Socket player2 = socket.accept();
				logText.append(new Date() + ": Player 2 joined session " + sessionNum + '\n');
				logText.append(new Date() + ": Player 2 IP Adress: " + player2.getInetAddress().getHostAddress() + '\n');
				new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2);
				
				// Start new session with player 1 and player 2
				logText.append(new Date() + ": Start a thread for session " + sessionNum++ + '\n');
				HandleASession game = new HandleASession(player1, player2);
				new Thread(game).start();
			}
		}
		catch (Exception ex) {
			System.err.println(ex);
		}
	}
	
	/**
	 * Creates a JPanel to display information about server activity.
	 */
	private void initGUI() {
		
		// Get the size of the default screen
	    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		
		// Server GUI
		logText  = new JTextArea();
		logText.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(logText);
		add(scrollPane, BorderLayout.CENTER);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(DIMENSIONS.x,DIMENSIONS.y);
		setTitle(TITLE_TEXT);
		setVisible(true);
		setLocation(dim.width/2 - getWidth()/2, dim.height/2 - getHeight()/2 - 200);
	}
}
